/*
 * © 2010 Autodata Solutions Company. All Rights Reserved
 * This source code is the confidential and proprietary information of Autodata Solutions Company.
 * The user shall not, in whole or in part, copy, publish, disclose or make any use of this source code
 * without the prior written consent of Autodata Solutions Company.
 */
Ext.ns('net.autodata.data.JsonRequest');
(function () {
	
	/**
	 * An Ajax Connection implmentation specifically for Json Requests
	 * @class JsonRequest
	 * @extends ASC.data.Connection
	 * @namespace net.autodata.data
	 */
	var JsonRequest = Ext.extend(ASC.data.Connection, {
		
		/**
		 * Execute the Ajax request
		 * @method request
		 * @param {Object} option Request parameters
		 */
		request: function (options)
		{
			//Force json request
			options = Ext.apply(options||{}, {handleAs: 'json'});
			JsonRequest.superclass.request.call(this, options);
		},
		
		/**
		 * @method handleResponse
		 * @private
		 */
		handleResponse: function (response)
		{
			var ioArgs = response.ioArgs;
			var options = ioArgs.options;
			var json = response.responseJSON;
			
			
			//Add the relevant XMLHttpRequest object so caller has access to the Response headers, etc
			ioArgs.xhr = this.xhr(response);
			
			//this.transId = false;
			this.fireEvent('requestcomplete', this, response, ioArgs);
			
			//Check to make sure there were no errors returned
			var result = json.result;
			var error = json.error;
			
			if (error == null || error.message === undefined) {
				Ext.callback(options.success, options.scope, [result.data, ioArgs]);
				Ext.callback(options.callback, options.scope, [result.data, true, ioArgs]);
			} else {				
				Ext.callback(options.failure, options.scope, [error, ioArgs]);
				Ext.callback(options.callback, options.scope, [error, false, ioArgs]);
			}
		},
		
		/**
		 * @method handleFailure
		 * @private
		 */
		handleFailure: function (response)
		{
			var ioArgs = response.ioArgs;
			var options = ioArgs.options;

			//Add the relevant XMLHttpRequest object so caller has access to the Response headers, etc
			var xhr = ioArgs.xhr = this.xhr(response);
			
			this.fireEvent('requestcomplete', this, response, ioArgs);
			
			var error = response.error;
			if (error === undefined) {
				error = {
					message: undefined,
					data: {}
				};
			}
			
			if (error.message === undefined) {
				error.message = xhr.error;
			}
			
			Ext.callback(options.failure, options.scope, [error, ioArgs]);
			Ext.callback(options.callback, options.scope, [error, false, ioArgs]);
		}
		
	});
	
	net.autodata.data.JsonRequest = JsonRequest;
})();